"use strict";

uk.logic = {
	users:{},
	seats:{},
	/** 当前选择的角色 */
	self:null,
	/** 我的其他角色 */
	otherroles:[],
	__inited:false,
	/**最后一次悬浮的牌 */
	__lastovercard:null,
	/**谁的轮次 */
	whoturn:-1,
	/**桌面上的牌 */
	deskcards:[],
	/**自己出的牌 */
	outcards:[],
	/**状态对象 */
	state:null,
	init: function(){
		if(this.__inited){
			console.warn('logic has initialized~~');
			return;
		}
		console.log('logic init');
		this.__inited = true;

		/** 关联下事件 */
		uk.netbind(uk.netevents.REGISTER,on_web_passport_action_callback,this,true);
		uk.netbind(uk.netevents.LOGIN,on_web_passport_action_callback,this,true);
		uk.netbind(uk.netevents.SWITCHROLE,this.on_switch_role,this,true);
		uk.netbind(uk.netevents.GAMEBEGIN,this.on_game_begin,this,true);
		uk.netbind(uk.netevents.GAMEEND,this.on_game_end,this,true);
		uk.netbind(uk.netevents.READY,this.on_user_ready,this,true);
		uk.netbind(uk.netevents.ENTER,this.on_user_enter,this,true);
		/**放置到最后面，因为这个会清除数据 */
		uk.netbind(uk.netevents.LEAVE,this.on_user_leave,this,false);
		uk.netbind(uk.netevents.OTHERENTER,this.on_other_enter,this,true);
		uk.netbind(uk.netevents.CUTBACK,this.on_cut_back,this,true);
		uk.netbind(uk.netevents.CUTOFF,this.on_cut_off,this,true);
		uk.netbind(uk.netevents.PROPCHANGE,this.on_prop_change,this,true);
		uk.netbind(uk.netevents.SETTURN,this.on_set_turn,this,true);
		uk.netbind(uk.netevents.SKIPROUND,this.on_skip_round,this,true);
		uk.netbind(uk.netevents.SKIPRDEAL,this.on_skip_deal,this,true);
		uk.netbind(uk.netevents.DEALCARD,this.on_deal_card,this,true);
		uk.netbind(uk.netevents.OUTCARD,this.on_user_out_card,this,true);
	},

	reset:function(){
		console.log('logic reset');
		/** 状态 */
		this.state = uk.game.state.getCurrentState();
	},

	on_switch_role:function(obj){
		if(obj.success){
			uk.logic.self = uk.create_role(obj.roleid,obj);
			uk.game.state.start('main');
		}
	},

	on_user_enter:function(obj){
		if(uk.game.state.current != 'play'){
			/** 尚不在房间里，需要开启消息缓存 */
			uk.netcache_enable(true);
			uk.game.state.start('play');
		}
		console.log('on_user_enter:',obj);
		if(obj.success){
			this.self.seat = obj.seat;
			this.users[this.self.id] = this.self;
			this.seats[obj.seat] = this.self;
		}
	},

	on_other_enter:function(obj){
		console.log('on_other_enter:',uk.countof(this.users),obj);
		var u = uk.create_role(obj.roleid,obj);
		this.users[obj.id] = u;
		this.seats[obj.seat] = u;
	},

	on_user_leave:function(obj){
		if(obj.id == this.self.id){
			/**如果是自己离开，则清空房间里的用户，但是保留自己的 */
			this.users = {};
			this.seats = {};
			this.users[this.self.id] = this.self;
		}else{
			delete this.seats[this.users[obj.id].seat];
			delete this.users[obj.id];
		}
		console.log('on_user_leave:',obj,this.users);
	},

	on_cut_off:function(obj){
		console.log('on_other_enter:',obj);
	},

	on_cut_back:function(obj){
		console.log('on_user_leave:',obj);
	},

	on_user_ready:function(obj){
		console.log('on_user_ready:',obj);
	},

	on_game_begin:function(obj){
		console.log('on_game_begin:',uk.game.state.current);
		/** 状态 */
		this.state = uk.game.state.getCurrentState();

		for(var i in this.seats){
			var u = this.seats[i];
			if(u == null) continue;
			u.handcards = [];
			u.outcards = [];
			u.remaincard = obj.cardnum[i];
			this.state.set_dealcard_remain(this.get_local_seat(u),u.remaincard);
		}
		this.deskcards = [];
		this.outcards = [];
		this.whoturn = -1;
	},

	on_game_end:function(obj){
		console.log('on_game_end:'+obj);
		uk.start_timer(30*1000,function(){
			uk.netsend(uk.netevents.LEAVE,{});
			uk.game.state.start('menu');
		});
		for(var i in this.self.handcards){
			var c = this.self.handcards[i];
			c.back.inputEnabled = false;
		}
	},

	on_prop_change:function(obj){
		var u = this.users[obj.id];
		if(u == undefined)
			return;
		console.log('prop change ',obj.changed.mask&0x8000,u.name,obj.changed.props);
		for(var k in obj.changed.props){
			if((obj.changed.mask&0x8000)==0&&u.props.hasOwnProperty(k))
				u.props[k] += obj.changed.props[k];
			else
				u.props[k] = obj.changed.props[k];
		}
		for(var k in obj.changed.buffadd){
			console.log('add buff',obj.changed.buffadd[i]);
			//u.buffs.push.apply(u.buffs,obj.changed.buffadd);
		}
		for(var k in obj.changed.buffdel){
			for(var i in u.buffs){
				if(u.buffs[i].id == obj.changed.buffdel[i]){
					console.log('remove buff',u.buffs[i].name);
					break;
				}
			}
		}
		for(var k in obj.changed.equipadd){

		}
		for(var k in obj.changed.equipdel){

		}
	},

	on_set_turn:function(obj){
		if(this.whoturn != -1){
			var r = this.seats[this.whoturn];
			var localseat = this.get_local_seat(r);
			for(var i in this.deskcards){
				var c = this.deskcards[i];
				c.back.inputEnabled = false;
				var t=uk.game.add.tween(c.back);
				t.onComplete.add(function(img,tw,card){
					card.back.visible = false;
				},this,0,c);
				t.to({x:uk.uidata.play.DEADCARDPOS[localseat].x,y:uk.uidata.play.DEADCARDPOS[localseat].y,width:uk.uidata.play.DEADCARDSIZE[localseat].cx,height:uk.uidata.play.DEADCARDSIZE[localseat].cy},300,null,true);
			}
			r.outcards.push.apply(r.outcards,this.deskcards);
		}
		this.whoturn = obj.turn;
		this.deskcards = [];
		this.outcards = [];
	},

	on_skip_round:function(obj){
		console.log('on_skip_round:'+obj);
	},

	on_skip_deal:function(obj){
		console.log('on_skip_deal:'+obj);
	},

	on_deal_card:function(obj){
		var newcards = [];
		for(var i in obj.cards){
			var c = uk.create_card(obj.cards[i]);
			this.state.cardlayer.add(c.back);
			newcards.push(c);
		}
		if(newcards.length > 0)
			this.__loop_deal_card(this.users[obj.id],newcards);
	},

	__loop_deal_card:function(r,newcards){
		var c = newcards[0];
		newcards.splice(0,1);
		var localseat = this.get_local_seat(r);
		var stpos = this.get_handcards_new_card_position(r,-1);

		r.remaincard --;
		this.state.set_dealcard_remain(localseat,r.remaincard);

		c.back.left = uk.uidata.play.POOLCARDPOS[localseat].x;
		c.back.top = uk.uidata.play.POOLCARDPOS[localseat].y;
		c.back.width=uk.uidata.play.POOLCARDSIZE.cx;
		c.back.height=uk.uidata.play.POOLCARDSIZE.cy;
		var t=uk.game.add.tween(c.back);
		if(r.id == this.self.id){
			t.onComplete.add(function(img,otween,r,c,remain){
				c.back.events.onInputUp.add(this.on_card_click,this,0,c);
				c.back.events.onInputOver.add(this.on_handcards_over,this,0,c);
				c.back.events.onInputOut.add(this.on_handcards_moveout,this);
				c.back.inputEnabled = true;
				c.back.ignoreChildInput = true;/**忽略子控件 */

				r.handcards.push(c);
				this.refresh_handcards_layout(r);

				if(remain.length > 0){
					this.__loop_deal_card(r,remain);
				}
			},this,0,r,c,newcards);
		}else{
			t.onComplete.add(function(img,otween,r,c,remain){
				r.handcards.push(c);
				this.refresh_handcards_layout(r);
				if(remain.length > 0){
					this.__loop_deal_card(r,remain);
				}
			},this,0,r,c,newcards);
		}
		t.to({x:stpos.x,y:stpos.y,width:uk.uidata.play.HANDCARDSSIZE[localseat].cx,height:uk.uidata.play.HANDCARDSSIZE[localseat].cy},100,null,true);
	},

	on_user_out_card:function(obj){
		if(obj.id != this.self.id){
			var r = this.users[obj.id];
			var c = uk.create_card(obj.card);
			this.state.cardlayer.add(c.back);

			var oldc = r.handcards[0];
			r.handcards.splice(0,1);
			this.refresh_handcards_layout(r);

			this.deskcards.push(c);
			c.back.x = oldc.back.x;
			c.back.y = oldc.back.y;
			c.back.width = oldc.back.width;
			c.back.height = oldc.back.height;
			c.back.bringToTop();
			oldc.back.destroy();
			oldc.back = null;

			var t = uk.game.add.tween(c.back);
			var pos = this.get_deskcards_new_card_position(this.deskcards.length-1);
			t.to({x:pos.x,y:pos.y,width:uk.uidata.play.DESKCARDSIZE.cx,height:uk.uidata.play.DESKCARDSIZE.cy},300,null,true);
			t.onComplete.add(function(img,otween,c){
				c.back.events.onInputOver.add(this.on_deskcards_over,this,0,c);
				c.back.events.onInputOut.add(this.on_deskcards_moveout,this);
				c.back.inputEnabled = true;
				c.back.ignoreChildInput = true;/**忽略子控件 */

				this.refresh_deskcards_layout();
			},this,0,c);
		}else{
			/** 超过1张牌的时候说明前面的牌出牌失败了。不要删掉 */
			if(this.outcards.length > 1){
				for(var i = 0;i < this.outcards.length-1;++i){
					var card = this.outcards[i];
					card.back.inputEnabled = true;
				}
				this.outcards.splice(0,this.outcards.length-1);
			}
			var c = this.outcards[0];
			this.outcards.splice(0,1);
			for(var i in this.self.handcards){
				var card = this.self.handcards[i];
				if(c.id == card.id){
					this.deskcards.push(card);
					card.back.events.destroy();
					this.self.handcards.splice(i,1);
					break;
				}
			}
			this.refresh_handcards_layout(this.self);

			var t = uk.game.add.tween(c.back);
			var pos = this.get_deskcards_new_card_position(this.deskcards.length-1);
			t.to({x:pos.x,y:pos.y,width:uk.uidata.play.DESKCARDSIZE.cx,height:uk.uidata.play.DESKCARDSIZE.cy},300,null,true);
			t.onComplete.add(function(img,otween,card){
				c.back.events.onInputOver.add(this.on_deskcards_over,this,0,c);
				c.back.events.onInputOut.add(this.on_deskcards_moveout,this);
				c.back.inputEnabled = true;
				c.back.ignoreChildInput = true;/**忽略子控件 */

				this.refresh_deskcards_layout();
			},this,0,c);
		}
	},

	on_card_click:function(img,evt,isOver,card){
		if(!isOver){
			return;
		}
		if(this.whoturn != this.self.seat){
			this.add_error_tip('对方出牌阶段，还未到您！');
			return;
		}
		if(card.template.cost > this.self.props.mp){
			this.add_error_tip('魔法值不足');
			return;
		}
		card.back.bringToTop();
		card.back.inputEnabled = false;
		this.outcards.push(card);
		this.__lastovercard = null;
		var enemy = this.get_enemy(this.self);
		if(enemy)
			uk.netsend(uk.netevents.OUTCARD,{card:card.template.id,target:enemy.id});
	},

	on_handcards_over:function(img,evt,card){
		this.on_handcards_moveout();
		this.__lastovercard = {card:card,x:img.x,y:img.y};
		uk.game.add.tween(card.back).to({y:card.back.y-10},100,null,true);
		this.refresh_handcards_layout(this.self);
	},

	on_handcards_moveout:function(){
		if(this.__lastovercard != null){
			this.__lastovercard.card.back.y = this.__lastovercard.y;
			//uk.game.add.tween(this.__lastovercard.card.back).to({y:this.__lastovercard.y},100,null,true);
			this.__lastovercard = null;
		}
	},

	on_deskcards_over:function(img,evt,card){
		this.on_deskcards_moveout();
		this.__lastovercard = {card:card,x:img.x,y:img.y};
		uk.game.add.tween(card.back).to({y:card.back.y-10},100,null,true);
		this.refresh_deskcards_layout();
	},

	on_deskcards_moveout:function(){
		if(this.__lastovercard != null){
			uk.game.add.tween(this.__lastovercard.card.back).to({y:this.__lastovercard.y},100,null,true);
			this.__lastovercard = null;
		}
	},

	get_deskcards_new_card_position:function(idx){
		idx = idx<0||idx>this.deskcards.length?this.deskcards.length:idx;
		if(this.deskcards.length <= 1){
			return {x:uk.uidata.play.DESKCARDSPOS.x+(uk.uidata.play.DESKCARDSWIDTH-uk.uidata.play.DESKCARDSIZE.cx)/2,y:uk.uidata.play.DESKCARDSPOS.y,xspace:uk.uidata.play.DESKCARDSIZE.cx};
		}
		var xspace = (uk.uidata.play.DESKCARDSWIDTH-uk.uidata.play.DESKCARDSIZE.cx)/(this.deskcards.length-1);
		xspace = xspace > uk.uidata.play.DESKCARDSIZE.cx?uk.uidata.play.DESKCARDSIZE.cx:xspace;
		var neww = xspace*(this.deskcards.length-1)+uk.uidata.play.DESKCARDSIZE.cx;
		var centerx = uk.uidata.play.DESKCARDSPOS.x+(uk.uidata.play.DESKCARDSWIDTH-neww)/2;
		return {x:centerx+xspace*idx,y:uk.uidata.play.DESKCARDSPOS.y,xspace:xspace};
	},

	get_handcards_new_card_position:function(r,idx){
		var handcards = r.handcards;
		var seat = this.get_local_seat(r);
		idx = idx<0||idx>handcards.length?handcards.length:idx;
		if(handcards.length <= 1){
			return {x:uk.uidata.play.HANDCARDSPOS[seat].x+(uk.uidata.play.HANDCARDSWIDTH-uk.uidata.play.HANDCARDSSIZE[seat].cx)/2,y:uk.uidata.play.HANDCARDSPOS[seat].y,xspace:uk.uidata.play.HANDCARDSSIZE[seat].cx};
		}
		var xspace = (uk.uidata.play.HANDCARDSWIDTH-uk.uidata.play.HANDCARDSSIZE[seat].cx)/(handcards.length-1);
		xspace = xspace > uk.uidata.play.HANDCARDSSIZE[seat].cx?uk.uidata.play.HANDCARDSSIZE[seat].cx:xspace;
		var neww = xspace*(handcards.length-1)+uk.uidata.play.HANDCARDSSIZE[seat].cx;
		var centerx = uk.uidata.play.HANDCARDSPOS[seat].x+(uk.uidata.play.HANDCARDSWIDTH-neww)/2;
		return {x:centerx+xspace*idx,y:uk.uidata.play.HANDCARDSPOS[seat].y,xspace:xspace};
	},

	refresh_deskcards_layout:function(){
		var stpos = this.get_deskcards_new_card_position(0);
		this.refresh_cards_layout(this.deskcards,stpos);
	},

	refresh_handcards_layout:function(r){
		var localseat = this.get_local_seat(r);
		var stpos = this.get_handcards_new_card_position(r,0);
		this.refresh_cards_layout(r.handcards,stpos);
	},

	refresh_cards_layout:function(cards,stpos){
		var selidx = cards.length;
		for(var i = 0;i < cards.length;++i){
			var c = cards[i];
			if(this.__lastovercard != null && this.__lastovercard.card.id == c.id){
				selidx = i;
				break;
			}
			c.back.bringToTop();
			var t=uk.game.add.tween(c.back);
			t.to({x:stpos.x+i*stpos.xspace,y:stpos.y},100,null,true);
		}

		for(var i = cards.length-1;i > selidx;--i){
			var c = cards[i];
			if(this.__lastovercard != null && this.__lastovercard.card.id == c.id)
				break;
			c.back.bringToTop();
			var t=uk.game.add.tween(c.back);
			t.to({x:stpos.x+i*stpos.xspace,y:stpos.y},100,null,true);
		}

		if(selidx < cards.length){
			var c = cards[selidx];
			c.back.bringToTop();
			var t=uk.game.add.tween(c.back);
			t.to({x:stpos.x+selidx*stpos.xspace,y:stpos.y-10},100,null,true);
		}
	},

	add_error_tip:function(msg){
		this.__add_tip_message(msg,uk.uidata.fontstyle.errortip);
	},

	add_normal_tip:function(msg){
		this.__add_tip_message(msg,uk.uidata.fontstyle.normaltip);
	},

	__add_tip_message:function(msg,fontstyle){
		var txt = uk.game.add.text(0,0,msg,fontstyle);
		this.state.tiplayer.removeAll(true,true);
		this.state.tiplayer.add(txt);
		txt.x = (uk.viewsize.cx-txt.width)/2;
		txt.y = (uk.viewsize.cy-uk.uidata.play.HANDCARDSSIZE[0].cy);
		var t = uk.game.add.tween(txt).to({y:txt.y-80},300,null,true);
		t.onComplete.add(function(img,otween){
			var t = uk.game.add.tween(img).to({y:img.y-50,alpha:0},500,null,true,2000);
			t.onComplete.add(function(img,otween){
				this.state.tiplayer.remove(img,true,true);
			},this);
		},this);
	},

	get_local_seat:function(r){
		var uc = uk.countof(this.users);
		return r.id == this.self.id ? 0:(uc+parseInt(r.seat)-parseInt(this.self.seat)) % uc;
	},

	get_seat:function(localseat){
		return (location + this.self.seat) % uk.countof(this.users);
	},

	get_enemy:function(p){
		for(var i in this.seats){
			var r = this.seats[i];
			if(r && r.id != p.id)
				return r;
		}
		return null;
	}
};